package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.GroupNameIDCache;
import cn.edu.nju.ws.sview.cache.UserNameIDCache;
import cn.edu.nju.ws.sview.views.Group;
import cn.edu.nju.ws.sview.views.User;

/**
 * Servlet implementation class Preference
 */
@WebServlet("/Preference")
public class Setting extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Setting() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String option=null;
		String json=null;
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		if(request.getParameter("groupset")!=null){
			json = request.getParameter("groupset");
			option="groupset";
		}else if(request.getParameter("dftgroup")!=null){
			json = request.getParameter("dftgroup");
			option="dftgroup";
		}else if(request.getParameter("groupList")!=null){
			json = request.getParameter("groupList");
			option="groupList";
		}else if(request.getParameter("preferLangs")!=null){
			json = request.getParameter("preferLangs");
			option="preferLangs";
		}

		if(option.equals("groupset")){
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String user = (String)regtJSON.get("user") ;
			int groupID = Integer.parseInt((String)(regtJSON.get("groupID")));
			int svdefault = -1;
			if(regtJSON.get("svdefault")!=null)
				svdefault = Integer.parseInt((String)(regtJSON.get("svdefault")));
			try {
				if(svdefault==1){
					int userID =UserNameIDCache.getInstance().getUserID(user);
					User.setDefaultGroup(userID, groupID);
				}else if(svdefault==0){
					//remove the default group id
					int userID =UserNameIDCache.getInstance().getUserID(user);
					User.setDefaultGroup(userID, 0);
				}
				String groupName = GroupNameIDCache.getInstance().getName(groupID);
				request.getSession().setAttribute("groupName", groupName);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 		}
		
		else if(option.equals("dftgroup")){
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String userName = (String)regtJSON.get("userName") ;
			int result = 0;
			try {
				int userID = UserNameIDCache.getInstance().getUserID(userName);
				result = User.getDefaultGroup(userID);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(result>0){
				String gname = Group.getGroupNameById(result);
				request.getSession().setAttribute("groupName", gname);
			}
			response.getWriter().print(result);
 		}
		
		else if(option.equals("groupList")){
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String userName = (String)regtJSON.get("userName") ;
			
		    User user = new User(userName);
		    JSONArray array = new JSONArray();
		    HashSet<Integer> groupsHashSet = user.getGroups();
		    for(Integer groupID:groupsHashSet){
		    	JSONObject jsObject = new JSONObject();
		    	jsObject.put("id", groupID) ;
		    	jsObject.put("groupName", Group.getGroupNameById(groupID));
		    	array.add(jsObject) ;
		    }
		    response.getWriter().print(array) ;
 		}
		else if(option.equals("preferLangs")){
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject qjson = (JSONObject) JSONValue.parse(str);
			String userName = (String)qjson.get("userName") ;
			JSONArray array = (JSONArray)qjson.get("langs");
		    User user = new User(userName);
		    HashSet<String> langs= new HashSet<String>();
		    for(int i=0;i<array.size();i++){
		    	String lang = (String)array.get(i);
		    	langs.add(lang);
		    }
		    
		    user.setPreferedLangsInDB(langs);
		}
	}

}
